package Lock_;


import java.util.concurrent.locks.ReentrantLock;

/*
* 解决线程安全问题的方式三：Lock锁 ——JDK5.0新增
* Lock是一个接口，我们想要使用它就要使用它的实现类
* */
public class LockTest implements Runnable {

    private int ticket  = 100;
    /*
    * 1、实列化ReentrantLock
    * */
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){

            try {
                /*
                 * 2、调用上锁方法
                 * */
                lock.lock();

                if (ticket > 0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+":"+ticket);
                    ticket--;
                }else {
                    break;
                }
            }finally {
                /*
                 * 3、调用解锁方法
                 * */
                lock.unlock();
            }


        }
    }
}
class LockTestMain{
    public static void main(String[] args) {
        LockTest lockTest = new LockTest();
        Thread t1 = new Thread(lockTest);
        Thread t2 = new Thread(lockTest);
        Thread t3 = new Thread(lockTest);
        t1.setName("窗口一");
        t2.setName("窗口二");
        t3.setName("窗口三");
        t1.start();
        t2.start();
        t3.start();

    }
}

